<template>
    <div style="display: inline-block;">
        <el-tree-select
            v-model="myId"
            :data="treeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            default-expand-all
            filterable 
            clearable
            @change="change1"
            :loading="loading"
            :disabled="props.disabled"
            popper-class="dept-tree-select"
            check-strictly
            style="width: 100%"
        />
        
    </div>
</template>
  
<script setup lang="ts">
import dataApi from '@/api/dataControl/index.ts';

const props = defineProps({
    property:String,
    index:Number,
    placeholder:String,
    modelValue:[Number,String],// 绑定 v-model 的值，接受 number 和 string 类型
    forDataPermSourceId:{
        type:Number,
        default:null
    },
    disabled: {
        type: Boolean,
        default: false
    },
});
const hasRight = ref(false);
const $emit = defineEmits(['update:modelValue','save']);// 定义 emit 事件

// 状态和观察者
const myId = ref<string | number | null>(null);
// 定义树节点的类型
interface TreeNode {
    id: number | null;
    name: string;
    children?: TreeNode[];
}
// 初始化 treeOptions 时明确指定类型
const treeOptions = ref<TreeNode[]>([]);

watch(() => props.modelValue,(newVal) => {
    myId.value = newVal ? Number(newVal) : ''; // 强制转成 number 类型
    // console.log('回显Id:',newVal);
},{ immediate:true });

const loading = ref(false)

onMounted(() => {
    init()
})
const init = async() => {
    await remoteMethod('');
}


const remoteMethod = async (query: string) => {
    treeOptions.value = []
    hasRight.value = false;
    if(props.property == 'forPermCommonId'){
        if(!props.forDataPermSourceId){
            ElMessage.error('缺少forDataPermSourceId');
            return;
        }
        try {
            loading.value = true;
            let results = await dataApi.searchCommon({
                "sourceId": props.forDataPermSourceId,
                "searchKey": query,
            }) as any;
            if (results) {
                treeOptions.value = results.data;
                // console.log('treeOptions:',treeOptions.value);
            }
        } catch (error) {
            throw new Error("接口调用失败"); 
        } finally {
            loading.value = false;
        }
    }
}
const deptName = ref('');
const findDeptName = (deptList: TreeNode[], deptId: number | string| null): string | undefined => {
    for (const dept of deptList) {
        if (dept.id == deptId) {
            return dept.name;
        }
        if (dept.children) {
            const result = findDeptName(dept.children, deptId);
            if (result) {
                return result;
            }
        }
    }
    return undefined;
};
 
const change1 = (val: any) => {
    // 查找treeOptions中id 与 val 匹配的对象
    if (val) {
        const selectedDeptName = findDeptName(treeOptions.value, val); // 调用时传递两个参数
        deptName.value = selectedDeptName?selectedDeptName:'';
    } else {
        deptName.value = '';
    }
    let subItem = {
        id: val,
        name: deptName.value,
    }
    let msg = {
        property: props.property,
        index: props.index, 
        value: val,
        item: subItem
    };
    $emit('update:modelValue',val);// 触发 v-model 更新
    $emit('save', msg);
}
const clear = () =>{
    myId.value = '';
    treeOptions.value = [];
}
defineExpose({ clear});
</script>
  
<style scoped lang="scss">
.rightStyle{ padding-left: 20px;color: var(--el-text-color-secondary);}
</style>
